function createInvoiceModel(data) {
	var invoice = data.getElementsByTagName("order");
	var arrInvoice = [];
	var orderId, userId, receiveAddress, receivePhoneNumber, orderDate, receiverName, shippingMethod, paymentMethod, totalPrice, status;
	for (var i = 0; i < invoice.length; i++) {
		orderId = invoice[i].getElementsByTagName("orderId")[0].childNodes[0].nodeValue;
		userId = invoice[i].getElementsByTagName("userId")[0].childNodes[0].nodeValue;
		receiveAddress = invoice[i].getElementsByTagName("receiveAddress")[0].childNodes[0].nodeValue;
		receivePhoneNumber = invoice[i].getElementsByTagName("receivePhone")[0].childNodes[0].nodeValue;
		orderDate = invoice[i].getElementsByTagName("orderDate")[0].childNodes[0].nodeValue;
		receiverName = invoice[i].getElementsByTagName("receiverName")[0].childNodes[0].nodeValue;
		shippingMethod = invoice[i].getElementsByTagName("shippingMethod")[0].childNodes[0].nodeValue;
		paymentMethod = invoice[i].getElementsByTagName("paymentMethod")[0].childNodes[0].nodeValue;
		totalPrice = invoice[i].getElementsByTagName("totalPrice")[0].childNodes[0].nodeValue;
		status = invoice[i].getElementsByTagName("status")[0].childNodes[0].nodeValue;

		arrInvoice[i] = {
			"orderId" : orderId,
			"userId" : userId,
			"receiveAddress" : receiveAddress,
			"receivePhoneNumber" : receivePhoneNumber,
			"orderDate" : orderDate,
			"receiverName" : receiverName,
			"shippingMethod" : shippingMethod,
			"paymentMethod" : paymentMethod,
			"totalPrice" : totalPrice,
			"status" : status,
		}
	}

	return new BookOrderPage(arrInvoice);
}

var BookOrderPage = function(orderList) {
	this.orderList = orderList;
}
var BookOrder = function(orderId, ownerId, totalPrice, orderDate, dateReceive, status) {
	this.orderId = orderId;
	this.ownerId = ownerId;
	this.totalPrice = totalPrice;
	this.orderDate = orderDate;
	this.dateReceive = dateReceive;
	this.status = status;
}
var BookOrderDetail = function(orderId, userId, receiveMessage, receivePhoneNumber, orderDate, receivePersonalName, shippingMethod, paymentMethod, price, status) {
	this.orderId = orderId;
	this.userId = userId;
	this.receiveMessage = receiveMessage;
	this.receivePhoneNumber = receivePhoneNumber;
	this.orderDate = orderDate;
	this.receivePersonalName = receivePersonalName;
	this.shippingMethod = shippingMethod;
	this.paymentMethod = paymentMethod;
	this.price = price;
	this.status = status;
}
var BookOrderDetailPerBook = function(bookName, bookAuthor, quantity, totalPrice) {
	this.bookName = bookName;
	this.bookAuthor = bookAuthor;
	this.quantity = quantity;
	this.totalPrice = totalPrice;
}
function showManageOrderPage(data) {
	var key = "invoice";
	addActive(key);
	var root = $id("invoiceContent");
	root.innerHTML = "";
	if (data.length > 0) {
		var nodeTable = createTable();
		nodeTable.setAttribute("id", "tableInvoice");

		var nodeThId = createNode("th");
		var idTh = createTextNode("Mã Hóa Đơn");
		nodeThId.appendChild(idTh);
		var nodeThAcc = createNode("th");
		var accTh = createTextNode("Tài khoản");
		nodeThAcc.appendChild(accTh);
		var nodeThTotal = createNode("th");
		var totalTh = createTextNode("Tổng tiền");
		nodeThTotal.appendChild(totalTh);
		var nodeThDate = createNode("th");
		var dateTh = createTextNode("Ngày mua hàng");
		nodeThDate.appendChild(dateTh);
		// var nodeThRelease = createNode("th");
		// var releaseTh = createTextNode("Ngày giao hàng");
		// nodeThRelease.appendChild(releaseTh);
		var nodeThStt = createNode("th");
		var SttTh = createTextNode("Tình trạng");
		nodeThStt.appendChild(SttTh);
		var nodeThDetails = createNode("th");

		var nodeThDelete = createNode("th");

		nodeTable.appendChild(nodeThId);
		nodeTable.appendChild(nodeThAcc);
		nodeTable.appendChild(nodeThTotal);
		nodeTable.appendChild(nodeThDate);
		//nodeTable.appendChild(nodeThRelease);
		nodeTable.appendChild(nodeThStt);
		nodeTable.appendChild(nodeThDetails);
		nodeTable.appendChild(nodeThDelete);

		for (var i = 0, j = data.length; i < j; i++) {
			var order = data[i]
			var row = document.createElement("tr");
			row.setAttribute("id", "orderIdInRow" + order.orderId);
			//cho từng column
			// this.orderId = orderId;
			// this.ownerId = ownerId;
			// this.totalPrice = totalPrice;
			// this.orderDate = orderDate;
			// this.dateReceive = dateReceive;
			// this.status = status;

			//column orderId
			var columnOrderId = document.createElement("td");
			var id = document.createTextNode(order.orderId);
			columnOrderId.appendChild(id);
			row.appendChild(columnOrderId);

			//cột owner Name

			var columnOwnerId = document.createElement("td");
			var owner = document.createTextNode(order.userId);
			columnOwnerId.appendChild(owner);
			row.appendChild(columnOwnerId);

			// cột total price

			var columnTotalPrice = document.createElement("td");
			var totalPrice = document.createTextNode(order.totalPrice);
			columnTotalPrice.appendChild(totalPrice);
			row.appendChild(columnTotalPrice);

			//cột order date

			var columnOrderDate = document.createElement("td");
			var orderDate = document.createTextNode(order.orderDate);
			columnOrderDate.appendChild(orderDate);
			row.appendChild(columnOrderDate);

			//cột status

			var columnStatus = document.createElement("td");
			var status = order.status;
			var statusString;
			if (status == '0') {
				statusString = "Chưa xử lý";
				status = document.createTextNode(statusString);
			} else if (status == '1') {
				statusString = "Đã xử lý";
				status = document.createTextNode(statusString);
			}
			columnStatus.appendChild(status);
			row.appendChild(columnStatus);

			//cột detail
			var columnDetail = document.createElement("td");
			var divDetail = createDiv();
			divDetail.addClass("orderDetail");
			var detail = document.createElement("span");
			var chuaXuly = document.createTextNode("Chi tiết");
			detail.style.cursor = "pointer";
			detail.style.color = "blue";
			detail.appendChild(chuaXuly);
			divDetail.appendChild(detail);
			columnDetail.addEventListener("click", function(event) {
				var currentrow = $id(event.currentTarget.parentNode.id);
				var cels = currentrow.getElementsByTagName("td");
				var id = cels[0].innerText;
				getOrderDetail(id);
			});

			columnDetail.appendChild(divDetail);
			row.appendChild(columnDetail);

			nodeTdDelete = createNode("td");
			nodeDivDelete = createDiv();
			nodeDelete = createNode("img");
			nodeDelete.setAttribute("src", "Image/delete_icon.png");
			nodeDelete.style.cursor = "pointer";
			nodeTdDelete.addEventListener("click", function(event) {
				var row = $id(event.currentTarget.parentNode.id);
				var cels = row.getElementsByTagName("td");
				var orderId = cels[0].innerText;
				var r = confirm("Bạn có muốn xóa đơn hàng có mã là " + orderId + " ?");
				if (r == true) {
					deleteOrder(orderId);
				}
			});
			nodeDivDelete.appendChild(nodeDelete);
			nodeTdDelete.appendChild(nodeDivDelete);
			row.appendChild(nodeTdDelete);

			nodeTable.appendChild(row);
		};
		root.appendChild(nodeTable);

		var divPaging = createDiv();
		divPaging.setAttribute("id", "pageInvoice");
		divPaging.setAttribute("class", "paging");
		var script = createNode("script");
		script.setAttribute("type", "text/javascript");
		script.innerHTML = "var pager = new Pager('tableInvoice', 10); pager.init(); pager.showPageNav('pager', 'pageInvoice'); pager.showPage(1);";
		root.appendChild(divPaging);
		root.appendChild(script);
	}
}

function callInvoiceService() {
	ajax.get({
		url : "http://localhost:8080/book-service/staff/manageOrder",
		success : function(data, xhr) {
			showPage("content-manageInvoice");
			var model = createInvoiceModel(data);
			if (model.orderList.length <= 0) {
				alert("Không có kết quả!");
			}
			showManageOrderPage(model.orderList);
		},
		failure : function(xhr) {
			if (xhr.status == 401) {
				alert("Bạn không có quyền truy cập vào trang này!\n Xin mời đăng nhập lại");
				doRequestFail();
			} else {
				alert("Có lỗi xảy ra. Xin thử lại!");
			}
		},
		abort : function(xhr) {
			callback.abort(xhr);
		}
	});
}

function getOrderDetail(id) {
	ajax.get({
		url : "http://localhost:8080/book-service/staff/manageOrder/getOrderDetail",
		param : {
			"txtOrderId" : id
		},
		success : function(data, xhr) {
			var arrInvoice = [];
			var orderId, userId, receiveAddress, receivePhoneNumber, orderDate, receiverName, shippingMethod, paymentMethod, totalPrice, status;

			orderId = data.getElementsByTagName("orderId")[0].childNodes[0].nodeValue;
			userId = data.getElementsByTagName("userId")[0].childNodes[0].nodeValue;
			receiveAddress = data.getElementsByTagName("receiveAddress")[0].childNodes[0].nodeValue;
			receivePhoneNumber = data.getElementsByTagName("receivePhone")[0].childNodes[0].nodeValue;
			receiverName = data.getElementsByTagName("receiverName")[0].childNodes[0].nodeValue;
			orderDate = data.getElementsByTagName("orderDate")[0].childNodes[0].nodeValue;
			shippingMethod = data.getElementsByTagName("shippingMethod")[0].childNodes[0].nodeValue;
			paymentMethod = data.getElementsByTagName("paymentMethod")[0].childNodes[0].nodeValue;
			totalPrice = data.getElementsByTagName("totalPrice")[0].childNodes[0].nodeValue;
			status = data.getElementsByTagName("status")[0].childNodes[0].nodeValue;

			arrInvoice = {
				"orderId" : orderId,
				"userId" : userId,
				"receiveAddress" : receiveAddress,
				"receivePhoneNumber" : receivePhoneNumber,
				"receiverName" : receiverName,
				"orderDate" : orderDate,
				"shippingMethod" : shippingMethod,
				"paymentMethod" : paymentMethod,
				"totalPrice" : totalPrice,
				"status" : status,
			}

			var model = new BookOrderPage(arrInvoice);
			showPage("content-orderDetail");
			createOrderDetailView(model.orderList);
			
		},
		failure : function(xhr) {
			if (xhr.status == 401) {
				alert("Bạn không có quyền truy cập vào trang này!\n Xin mời đăng nhập lại");
				doRequestFail();
			} else {
				alert("Có lỗi xảy ra. Xin thử lại!");
			}
		},
		abort : function(xhr) {
			callback.abort(xhr);
		}
	});
}

function searchOrder() {
	var key = document.getElementById("txtSearchOrder").value;
	ajax.get({
		url : "http://localhost:8080/book-service/staff/manageOrder/searchOrder",
		param : {
			"txtOrderId" : key
		},
		success : function(data, xhr) {
			var model = createInvoiceModel(data);
			if (model.orderList.length <= 0) {
				alert("Không có kết quả!");
			}
			showManageOrderPage(model.orderList);
		},
		failure : function(xhr) {
			if (xhr.status == 401) {
				alert("Bạn không có quyền truy cập vào trang này!\n Xin mời đăng nhập lại");
				doRequestFail();
			} else {
				alert("Có lỗi xảy ra. Xin thử lại!");
			}
		},
		abort : function(xhr) {
			callback.abort(xhr);
		}
	});
}

function deleteOrder(id) {
	ajax.del({
		url : "http://localhost:8080/book-service/staff/manageOrder",
		param : {
			"txtOrderId" : id
		},
		success : function() {
			alert("Xóa hóa đơn có mã " + id + " thành công");
			showPage("content-manageInvoice");
			callInvoiceService();
		},
		failure : function(xhr) {
			if (xhr.status == 401) {
				alert("Bạn không có quyền truy cập vào trang này!\n Xin mời đăng nhập lại");
				doRequestFail();
			} else {
				alert("Có lỗi xảy ra. Xin thử lại!");
			}
		},
		abort : function(xhr) {
			callback.abort(xhr);
		}
	});
}
